package cn.dansj.handler.interfaces;

import cn.dansj.annotation.MarkAsApi;
import cn.dansj.bean.CurrentThreadLocalUserInfo;
import cn.dansj.common.utils.bean.Return;
import cn.dansj.entity.User;
import cn.dansj.service.UserService;
import cn.dansj.common.context.ApplicationContextProvider;
import cn.dansj.common.utils.transfer.DateTime;
import cn.dansj.common.utils.transfer.GetTime;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.common.utils.transfer.RandomUtils;
import cn.dansj.handler.InterfaceHandler;
import cn.dansj.utils.project.ProjectUtils;

import java.sql.Timestamp;
import java.util.Map;

@SuppressWarnings("all")
@MarkAsApi(nestingInMap = false)
public class UserSign extends InterfaceHandler {
    private static final UserService userService = ApplicationContextProvider.getBean(UserService.class);

    enum SignFrom {
        WebSite(1, 1),
        WxMp(2, 2),
        NoData(0, 0);

        private final int code;
        private final int points;

        SignFrom(int code, int points) {
            this.code = code;
            this.points = points;
        }

        public static SignFrom get(int code) {
            for (SignFrom value : values()) {
                if (value.code == code) {
                    return value;
                }
            }
            return NoData;
        }
    }

    private static final String sql = "insert into x_user_points values(?,?,?,?,?)";

    @Override
    public Object execute(Map<String, Object> paramsMap) {
        final String sequence = CurrentThreadLocalUserInfo.getCurrentThreadLocalUserInfo().getCacheToken().getSequence();
        final User user = userService.getUserBySequence(sequence);
        final Timestamp now = GetTime.dbTimestamp();
        final String from = Transformation.toString(paramsMap.get("from"));
        final int fromCode = Transformation.parseInt(from.length() == 31 ? from.charAt(15) : "0");
        if (user.getLastSignDate() == null || DateTime.getInstance(user.getLastSignDate().getTime()).compareTo(DateTime.getInstance().trunc()) == -1) {
            user.setLastSignDate(now);
            user.setUpdateTime(now);
            final SignFrom signFrom = SignFrom.get(fromCode);
            user.setPoint(user.getPoint() + signFrom.points);
            userService.save(user);
            jdbcTemplate.update(sql, RandomUtils.sequence(), user.getSequence(), now, fromCode, signFrom.points);
            // 更新token中的用户信息
            ProjectUtils.updateUserInterfaceTokenInfo(user);
            return Return.T(true, "签到成功");
        } else {
            return Return.T(false, "今日已签到").setResponseCode(550);
        }
    }
}
